#!/bin/sh -e

version="$1"

# passing the kernel version is required
if [ -z "${version}" ] ; then
	echo >&2 "W: zz-uenv_txt: ${DPKG_MAINTSCRIPT_PACKAGE:-kernel package} did not pass a version number"
	exit 2
fi

if [ -f /boot/uEnv.txt ] ; then
	unset older_kernel
	older_kernel=$(cat /boot/uEnv.txt | sed 's/ /\n/g' | grep -v '#' | grep 'uname_r=' | awk -F"=" '{print $2}' || true)

	if [ ! "x${older_kernel}" = "x" ] ; then
		if [ ! "x${older_kernel}" = "x${version}" ] ; then
			echo "zz-uenv_txt: Updating /boot/uEnv.txt [uname_r=${version}]"
			sed -i -e "s:uname_r=$older_kernel:uname_r=$version:g" /boot/uEnv.txt
		fi
	else
		echo "uname_r=${version}" >> /boot/uEnv.txt
	fi
fi

udir="/boot/uboot/boot"
if [ -f ${udir}/uEnv.txt ] ; then
	unset older_kernel
	older_kernel=$(cat ${udir}/uEnv.txt | sed 's/ /\n/g' | grep -v '#' | grep 'uname_r=' | awk -F"=" '{print $2}' || true)
	unset zreladdr
	zreladdr=$(cat ${udir}/uEnv.txt | sed 's/ /\n/g' | grep -v '#' | grep 'zreladdr=' | awk -F"=" '{print $2}' || true)

	if [ "x${older_kernel}" = "xcurrent" ] ; then

		if [ -f ${udir}/vmlinuz-current ] ; then
			rm -f ${udir}/vmlinuz-current || true
			cp /boot/vmlinuz-${version} ${udir}/vmlinuz-current
		fi

		if [ "${zreladdr}" ] ; then
			if [ -f ${udir}/uImage ] ; then
				rm -rf ${udir}/uImage || true
				mkimage -A arm -O linux -T kernel -C none -a ${zreladdr} -e ${zreladdr} -n ${version} -d ${udir}/vmlinuz-current ${udir}/uImage
			fi
		fi

		if [ -f ${udir}/initrd.img-current ] ; then
			rm -f ${udir}/initrd.img-current || true
			cp /boot/initrd.img-${version} ${udir}/initrd.img-current
		fi

		if [ -f ${udir}/uInitrd ] ; then
			rm -rf ${udir}/uInitrd || true
			mkimage -A arm -O linux -T ramdisk -C none -a 0 -e 0 -n initramfs -d ${udir}/initrd.img-current ${udir}/uInitrd
		fi

		if [ -d ${udir}/dtbs/current/ ] ; then
			rm -rf ${udir}/dtbs/current/ || true
			mkdir -p ${udir}/dtbs/current/

			if [ -d /boot/dtbs/${version}/ ] ; then
				cp /boot/dtbs/${version}/*.dtb ${udir}/dtbs/current/
			else
				if [ -d /usr/lib/linux-image-${version}/ ] ; then
					cp /usr/lib/linux-image-${version}/*.dtb ${udir}/dtbs/current/
				else
					if [ -d /lib/firmware/${version}/device-tree/ ] ; then
						cp /lib/firmware/${version}/device-tree/*.dtb ${udir}/dtbs/current/
					fi
				fi
			fi
		fi
		echo "zz-uenv_txt: Updating boot drive for: [${version}]"
	fi
fi
